#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by PyCharm.
# @Project: Code_Clone_Detection_Educoder
# @File: mysql_pool.py
# @Description: 
# @Time: 2018/12/12 15:46
# @Author: ljz

import pymysql
from dbutils.pooled_db import PooledDB


class MysqlPool:

    def __init__(self):
        self.__pool = PooledDB(creator=pymysql,
                               mincached=2,
                               host='127.0.0.1',
                               port=3306,
                               user='root',
                               password='',
                               database='',
                               charset='utf8mb4')

    def _execute(self, sql, param=None):
        connect = self.__pool.connection()
        cursor = connect.cursor()
        try:
            cursor.execute(sql)
            connect.commit()
            if param == 'select_one':
                result = cursor.fetchone()
            elif param == 'select_all':
                result = cursor.fetchall()
            else:
                result = None
            cursor.close()
            connect.close()
            return result
        except Exception as e:
            print(e)
            connect.rollback()
            cursor.close()
            connect.close()
            return None

    def insert(self, sql):
        self._execute(sql)

    def update(self, sql):
        self._execute(sql)

    def select_one(self, sql):
        return self._execute(sql, 'select_one')

    def select_all(self, sql):
        return self._execute(sql, 'select_all')


mysql_operator = MysqlPool()
